package controller;

import java.sql.ResultSet;
import data.DatabaseGateway;
import misc.Configurations;
import misc.Logger;
import misc.Logger.LogType;

public class FileDeletionController {
    //Attempt to delete file from filesystem, returns:
    //True = deleted, purging file from file system
    //False = cannot delete, will delete automatically
    public boolean purgeFileNow(long fileID)
    {
        boolean result=false;
        try
        {
            String query=
                    "SELECT * FROM IPSERVING WHERE DownloadingFileID="+fileID;
            String query1="SELECT * FROM FILES WHERE FileID="+fileID+
                                " AND isDeleted=true";
            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                    Configurations.DatabaseName);
            
            int n=gw.executeCount(query1);
            if(n>=1)//Deleted already
                return true;
            
            gw.startTransaction();
            int c = gw.executeCount(query);
            
            if(c<=0)//No one downloads
            {
                String q="SELECT FilePath FROM FILES WHERE FileID="+fileID;
                ResultSet rs = gw.executeQuery(q);
                rs.next();String filePath=rs.getString("FilePath");
                if(purgeFile(filePath))
                {
                    String update_q="UPDATE FILES SET isDeleted=true "+
                                        "WHERE FileID="+fileID;
                    gw.executeUpdate(update_q);
                    result=true;
                }
                else
                {
                    Logger.write("Unable to purge the file NOW ("+fileID+
                            ")!",LogType.warning);
                }
            }
            else
            {
                String q="INSERT INTO PENDINGFILES VALUES("+fileID+")";
                gw.executeUpdate(q);
                result=false;
            }
            
            gw.commitTransaction();
            gw.closeConnection();
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),LogType.error);
        }
        
        return result;
    }

    public void purgePendingFile(long fileID)
    {
        try
        {
            String query="SELECT * FROM PENDINGFILES WHERE FileID="+fileID;
            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                    Configurations.DatabaseName);
            
            int c=gw.executeCount(query);
            if(c<=0)
                return;
            
            String query1="SELECT FilePath FROM FILES WHERE FileID="+fileID;
            ResultSet rs = gw.executeQuery(query1);
            while(rs.next())
            {
                String path=rs.getString("FilePath");
                
                if(purgeFile(path))
                {
                    String delete_q="DELETE FROM PENDINGFILES WHERE "+
                                        "FileID="+fileID;
                    String update_q="UPDATE FILES SET isDeleted=true "+
                                "WHERE FileID="+fileID;
                    
                    gw.startTransaction();
                    gw.executeUpdate(update_q);
                    gw.executeUpdate(delete_q);
                    gw.commitTransaction();
                }
                else
                {
                    Logger.write("Unable to delete the pending file ("+fileID+
                            ","+path+")!",LogType.warning);
                }
            }
            gw.closeConnection();
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),LogType.error);
        }
    }

    public int purgeExpiredFiles()
    {
        int num_deleted=0;
        
        try
        {
            String query="SELECT FILES.FileID,FILES.FilePath from FILES,"+
                    "UPLOADLOGS WHERE FILES.FileID=UPLOADLOGS.FileID AND "+
                    "FILES.isDeleted=false AND (UNIX_TIMESTAMP(now())-"+
                    "UNIX_TIMESTAMP(UPLOADLOGS.FinishTimeDate))>=60*"+
                    Configurations.AvailableTime;
            
            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                    Configurations.DatabaseName);
            
            ResultSet rs = gw.executeQuery(query);
            
            while(rs.next())
            {
                long fileID=rs.getLong("FileID");
                String path=rs.getString("FilePath");
                
                if(purgeFile(path))
                {
                    String update_q="UPDATE FILES SET isDeleted=true "+
                                        "WHERE FileID="+fileID;
                    num_deleted+=gw.executeUpdate(update_q);
                }
                else
                {
                    Logger.write("Unable to purge the expired file ("+fileID+
                                                ","+path+")!",LogType.warning);
                }
            }
            
            gw.closeConnection();
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),LogType.error);
        }
        
        return num_deleted;
    }

    private boolean purgeFile(String filePath)
    {
        try
        {   
            java.io.File file = new java.io.File(filePath);
            return file.delete();
        }catch(Exception e)
        {
            Logger.write(e.getMessage(),Logger.LogType.error);
        }
        
        return false;
    }
}
